public class IPAddressAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
YourViewModel yourviewmodel = (YourViewModel)validationContext.ObjectInstance;
const string regexPattern = @"^([\d]{1,3}\.){3}[\d]{1,3}$";
var regex = new Regex(regexPattern);
if (string.IsNullOrEmpty(yourviewmodel.IpAddress))
{
return new ValidationResult("IP address is null");
}
if (!regex.IsMatch(yourviewmodel.IpAddress )|| yourviewmodel.IpAddress.Split('.').SingleOrDefault(s => int.Parse(s) > 255)!=null)
return new ValidationResult("Invalid IP Address");
return ValidationResult.Success;
}
}
// use
[IPAddressAttribute]
[Display(Name = "IP Address")]
public string IpAddress { get; set; }